home *** CD-ROM | disk | FTP | other *** search
- Path: isis.interpac.net!stacys
- From: stacys@isis.interpac.net (Stacy Sherman)
- Newsgroups: comp.lang.c
- Subject: Re: Newbie question: Is this code OK?
- Date: 18 Jan 1996 21:33:40 GMT
- Organization: Inter-Pacific Networks
- Message-ID: <4dmebk$foq@pegasus.interpac.net>
- References: <4di986$fk1@pegasus.interpac.net> <30FDDAC8.D79@e-tex.com>
- NNTP-Posting-Host: isis.interpac.net
- X-Newsreader: TIN [version 1.2 PL2]
-
- Thanks everyone for all your comments. It seems that the code was
- generally OK, except for 1 error which one of you caught and made itself
- known to me after I changed the program to check for '\0' instead of
- i<length. The second for loop should have an && between the i<length and
- the ((string[i]... parts. I'm still not real clear on this, I guess the
- comma between two conditions acts as an 'or' instead of an 'and'?
-
- Jos, in the netherlands came up with a simpler way to do this:
-
- for (; *string; string++)
-
- if (isspace(*string))
- state= 1;
- else if (state) {
- num_words++;
- state= 0;
- }
-
- return num_words;
- State being = 1 means it's reading white space. If you wanted, you could
- still replace the isspace with explicitly checking for the three chars
- like I did, and change to an array instead of a pointer.
-
- Other points:
-
- I know that strings are normally *char and that arrays are normally
- terminated by '\0' but the program called for an array where the length
- was explicitly stated. Everyone mentioned that there's an isspace or
- iswhite function but I figured it would be cheating to use it.
-
- Thanks alot. I'm sure you haven't heard the last of me :)
-
- Stacy
-
- smelly@e-tex.com wrote:
- : > Do I need the empty {} after a for loop that has no body? I assumed >
- : > if I didn't, the loop would execute the next statement after it.
-
-
- : > for (; i<length, ((string[i]!='\n') &&
- : > (string[i]!='\t') &&
- : > (string[i]!=' ')); i++)
- : > /* and skip past any other */
- : > /* chars that may be there */
- : > { } /* loop does all work, nothing inside body */
-
- : I am also new to C programming; however, I think I can make one
- : suggestion. Since your second for loop does all the work and you don't
- : need a body, you can write it like this.
-
- : for ( ; i<length, ((string[i]!='\n') &&
- : (string[i]!='\t') &&
- : (string[i]!=' ')); i++);
-
- : Placing the semi-colon at the end of the loop will prevent it from
- : running the next statement following the loop until after it has
- : processed to a point where the condition if false. I believe this will
- : work. Good luck and have fun! :-)
-
- : smelly@e-tex.com
- : Smelly Dog
-